// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"

void freerange(void *pa_start, void *pa_end);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};


//每个cpu使用独立的链表，对应一份freelist和lock
struct kmem{
  struct spinlock lock;
  struct run *freelist;
} ;
struct kmem kmem[NCPU];


//初始化kmem.lock锁
void
kinit()
{
  
  int i;
  //初始化kmem时将每个cpu对应kmem[i]都初始化
  for (i=0;i<NCPU;i++){
  initlock(&kmem[i].lock,"kmem");
  }
  //end也就是虚拟地址的kernel data处，freerange将所有可用内存分配给运行freerange的CPU，也就是当前的cpu。
  freerange(end, (void*)PHYSTOP);
}


//将内存划分为单位为1页大小的空间，1页为4kb
void
freerange(void *pa_start, void *pa_end)
{
  
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
    kfree(p);

}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
//将所有空闲页用链表kmem.freelist来管理
//回收一页物理内存，并将这一页内存全部设置为1，再添加到kmem.freelist链表中
void
kfree(void *pa)
{
  struct run *r;
 

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);
  

  r = (struct run*)pa;
  push_off();//关闭中断
  int i=cpuid();//cpu序号
  acquire(&kmem[i].lock);
  r->next = kmem[i].freelist;//将1页物理内存加到空闲链表头
  kmem[i].freelist = r;
  release(&kmem[i].lock);
  pop_off();//打开中断
 

}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
//分配1页物理内存，并将这一页内存从kmem.freelist划分出去
void *
kalloc(void)
{
  struct run *r;
  push_off();
  int i=cpuid();
  acquire(&kmem[i].lock);
  r = kmem[i].freelist;
  if(r)
  {
    kmem[i].freelist = r->next; 
  }
  release(&kmem[i].lock);

//在当前CPU的空闲链表（freelist ）为空，其他链表不为空的
//情况下，可以从其他CPU的空闲链表中窃取空闲内存；

  if(!r)
  {
     for(int j=0;j<NCPU;j++)
     {
       if(j!=i)
       {
          acquire(&kmem[j].lock);
          if(kmem[j].freelist)
	  {
	      r=kmem[j].freelist;
              kmem[j].freelist=r->next; 	      
	      release(&kmem[j].lock);
	      break;
	  }
          release(&kmem[j].lock);
       }
     }
  }
  
  pop_off();

  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
